package com.demo.blog.controller;

import com.demo.blog.model.Blog;
import com.demo.blog.model.Result;
import com.demo.blog.service.BlogService;
import com.demo.blog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-07-24
 * Time: 11:48
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;

    @RequestMapping("/getlist")
    public List<Blog> blogs(){
        return blogService.getBlogList();
    }

    /*
     * 发布博客
     */
    @RequestMapping("/add")
    public Result publishBlog(String title, String content, HttpServletRequest request){
        //从token中获取userId
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId==null || userId<0){
            return Result.fail("用户未登录",false);
        }
        //插入博客
        Blog blogInfo = new Blog();
        blogInfo.setUserId(userId);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogService.insertBlog(blogInfo);
        return Result.success(true);
    }
    /**
     * 获取博客详情
     */
    @RequestMapping("/getBlogDetail")
    public Blog getBlogDetail(Integer blogId,HttpServletRequest request){
        Blog blogInfo = blogService.getBlogDetail(blogId);
        //判断作者是否为登录用户
        //从token中获取userId
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId!=null && userId==blogInfo.getUserId()){
            blogInfo.setLoginUser(true);
        }
        return blogInfo;
    }

    /**
     * 编辑博客
     */
    @RequestMapping("/update")
    public boolean updateBlog(Integer id, String title, String content){
        Blog blogInfo = new Blog();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        //根据博客ID去更新数据
        blogInfo.setId(id);
        /**
         * 判断是否为作者本人
         * 从token中获取登录用户
         * 更新的sql: id = ? and userId= ?(登录用户)
         */
        blogService.updateBlog(blogInfo);
        return true;
    }
    /**
     * 删除博客
     */
    @RequestMapping("/delete")
    public boolean deleteBlog(Integer blogId){
        /**
         * 判断是否为作者本人
         * 需要获取登录用户和当前作者
         * 登录用户从token中获取
         * 当前作者, 需要再查一次数据库, 进行判断
         */
        blogService.delete(blogId);
        return true;
    }
}
